package com.goblin.model.base;

import java.io.Serializable;

import javax.persistence.EntityManager;

import com.goblin.common.response.PageHelper;
import com.goblin.common.response.Paged;
import com.querydsl.core.SimpleQuery;
import com.querydsl.core.types.dsl.PathBuilder;
import com.querydsl.core.types.dsl.PathBuilderFactory;
import com.querydsl.jpa.impl.JPAQueryFactory;
import org.springframework.data.jpa.repository.support.Querydsl;
import org.springframework.data.jpa.repository.support.SimpleJpaRepository;

public abstract class BaseRepositoryImpl<T, D extends Serializable>
		extends SimpleJpaRepository<T, D> implements BaseRepository<T, D> {
	protected final EntityManager entityManager;

	protected JPAQueryFactory jpaQueryFactory;

	private final PathBuilder<?> builder;

	private Querydsl querydsl;

	//父类没有不带参数的构造方法，这里手动构造父类
	public BaseRepositoryImpl(Class<T> domainClass, EntityManager entityManager) {
		super(domainClass, entityManager);
		this.entityManager = entityManager;
		jpaQueryFactory = new JPAQueryFactory(entityManager);
		this.builder = (new PathBuilderFactory()).create(domainClass);
		this.querydsl = new Querydsl(entityManager, this.builder);
	}

	protected SimpleQuery getQuerydsl(PageHelper pageable, SimpleQuery query) {
		int offset = (pageable.getPage() - 1) * pageable.getSize();
		int limit = pageable.getSize();

		query = query.offset(offset).limit(limit);

		return query;
	}
}
